package cn.lctvu.dao;

import cn.lctvu.bean.User;
import cn.lctvu.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDao {
    private QueryRunner runner=new QueryRunner(DataSourceUtils.getDataSource());
    public User getUserByNameAndPass(String username,String password) throws SQLException {
        String sql="select * from user where username=? and password=?";
       User user= runner.query(sql,new BeanHandler<>(User.class),username,password);
       return user;
    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     * @throws SQLException
     */
    public boolean deleteUserById(int id) throws SQLException {
        String sql="delete from user where id=?";
        int n=runner.update(sql,id);
        if (n > 0) {

            return true;
        }else {
            return false;
        }
    }

    /**
     * 更新用户
     * @param user
     * @return
     * @throws SQLException
     */
    public boolean updateUser(User user) throws SQLException {
        String sql="update user set username=?,password=?,tdate=?,email=? where id=?";
      int n= runner.update(sql,user.getUsername(),user.getPassword(),user.getTdate(),user.getEmail(),user.getId());
      if(n>0){
          return true;
      }else {
          return false;
      }
    }

    /**
     * 查询所有用户
     * @return
     * @throws SQLException
     */
    public List<User> findAllUser() throws SQLException {
        String sql="select * from user";
       List<User> list= runner.query(sql,new BeanListHandler<>(User.class));
       return list;
    }
    /**
     * 按id查询User对象
     * @param id
     * @return
     * @throws SQLException
     */
    public User findUserById(int id) throws SQLException {
        String sql="select * from user where id=?";
       User user= runner.query(sql,new BeanHandler<>(User.class),id);
       return user;
    }
    /**
     * 添加用户
     * @param user
     * @return
     * @throws SQLException
     */
    public boolean addUser(User user) throws SQLException {

        String sql="insert into user(username,password,tdate,email) values(?,?,?,?)";
        int n=runner.update(sql,user.getUsername(),user.getPassword(),user.getTdate(),user.getEmail());
        if(n>0){
            return true;
        }
        return  false;
    }
}
